#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/7 14:11
# @Author  : CoderCharm
# @File    : views.py
# @Software: PyCharm
# @Desc    :
"""

"""
import re
from datetime import timedelta
from typing import Any, Union

from flask import make_response
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse,FileResponse,Response
from core import security
from api.common import deps
from api.utils import response_code
from api.common.logger import logger
from core.config import settings

from core.security import verify_password
from .schemas import user_schema, token_schema
from .crud import curd_user
import captcha
from api.utils.my_redis import MyRedis
from api.utils.captcha.captcha.captcha import captcha

router = APIRouter()

@router.get("/img_code",summary="获取图形验证码")
async def img_code(uuid:str):
    name, text, image = captcha.generate_captcha()
    MyRedis().set_str(uuid, text)
    return Response(image,media_type='image/png')

@router.get('/msg_code',summary="发送短信验证码")
async def msg_code(
        db:Session = Depends(deps.get_db),
        mobile:int=0,
        imgcode:str="",
        uuid:str=""
):
    data = curd_user.send_message(db=db,mobile=mobile,imgcode=imgcode,uuid=uuid)
    if data['code'] == 200:
        return response_code.resp_200(message=data['msg'])
    else:
        return response_code.resp_401(message=data['msg'])


@router.post("/login", summary="用户登录", response_model=token_schema.RespToken)
async def login_access_token(
        user_info:user_schema.UserPhoneAuth,
        db:Session = Depends(deps.get_db)
) -> Any:
    """
    用户登录
    :param db:
    :param user_info:用户账号信息
    :return:
    """
    # 验证输入信息
    recode = curd_user.username_verify(account=user_info.username,password=user_info.password,msg_code=user_info.msgcode)
    if recode=='1001':
        return response_code.resp_500(message='用户名或者密码为空')
    elif recode=='1002':
        return response_code.resp_500(message='手机号格式不符')
    elif recode == "1003":
        return response_code.resp_401(message="短信验证码错误")
    # 验证用户
    user = curd_user.authenticate(db=db,account=user_info.username, password=user_info.password)
    if not user:
        return response_code.resp_500(message="用户名或者密码错误")

    return response_code.resp_200(data=user)
